<script lang="ts">
  import type { LlmProviderInfo } from "$lib/api/ai_provider/ai_provider";
  import {
    add_llm_provider,
    update_llm_provider,
  } from "$lib/api/ai_provider/ai_provider_admin";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import { Modal, Switch } from "@skeletonlabs/skeleton-svelte";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    provider?: LlmProviderInfo;
    onCancel: () => void;
    onOk: () => void;
  }
  let props: ModalProps = $props();

  let providerId = $state(props.provider?.provider_id ?? "");
  let name = $state(props.provider?.name ?? "");
  let needApiKey = $state(props.provider?.need_api_key ?? false);
  let defaultAddr = $state(props.provider?.default_addr ?? "");

  const valid = $derived(() => {
    if (providerId.trim() == "") {
      return false;
    }
    if (name.trim() == "") {
      return false;
    }
    if (
      (defaultAddr.startsWith("http://") ||
        defaultAddr.startsWith("https://")) == false
    ) {
      return false;
    }
    return true;
  });

  async function addProvider() {
    await request(
      add_llm_provider({
        admin_session_id: userStore.adminUserSession,
        provider_info: {
          provider_id: providerId,
          name: name.trim(),
          need_api_key: needApiKey,
          default_addr: defaultAddr,
        },
      })
    );
    toast.create({
      title: "成功",
      description: "增加大模型供应商成功!",
      type: "success",
    });
    props.onOk();
  }

  async function updateProvider() {
    await request(
      update_llm_provider({
        admin_session_id: userStore.adminUserSession,
        provider_info: {
          provider_id: providerId,
          name: name.trim(),
          need_api_key: needApiKey,
          default_addr: defaultAddr,
        },
      })
    );
    toast.create({
      title: "成功",
      description: "更新大模型供应商成功!",
      type: "success",
    });
    props.onOk();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onCancel();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">
        {props.provider == undefined ? "增加供应商" : "更新供应商"}
      </h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onCancel()}
      >
        <X />
      </button>
    </header>

    <label class="label">
      <span class="label-text">供应商ID</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="text"
        bind:value={providerId}
        disabled={props.provider != undefined}
        placeholder="请输入供应商ID"
      />
    </label>

    <label class="label">
      <span class="label-text">供应商名称</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="text"
        bind:value={name}
        placeholder="请输入供应商名称"
      />
    </label>

    <label class="flex gap-2 items-center">
      <span class="label-text">需要ApiKey</span>
      <Switch
        name="needApiKey"
        checked={needApiKey}
        onCheckedChange={(detail) => (needApiKey = detail.checked)}
        controlInactive="bg-surface-300-700"
        controlBase="m-0"
        controlHeight="h-[16px]"
        controlWidth="w-[32px]"
      />
    </label>

    <label class="label">
      <span class="label-text">Api地址</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="text"
        bind:value={defaultAddr}
        placeholder="请输入Api地址"
      />
      <span class="text-error-800-200 text-sm">
        {#if defaultAddr.length > 0 && defaultAddr.startsWith("http://")}
          &nbsp;
        {:else if defaultAddr.length > 0 && defaultAddr.startsWith("https://")}
          &nbsp;
        {:else if defaultAddr.length == 0}
          &nbsp;
        {:else}
          Api地址必须是http://或https://开头
        {/if}
      </span>
    </label>

    <footer class="flex justify-end gap-4">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => props.onCancel()}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-600-400"
        disabled={!valid()}
        onclick={() => {
          if (props.provider == undefined) {
            addProvider();
          } else {
            updateProvider();
          }
        }}>{props.provider == undefined ? "增加" : "更新"}</button
      >
    </footer>
  {/snippet}
</Modal>
